﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using TtfLibrary.CommonStructures;

namespace TtfLibrary
{
    public class TtfFile
    {
        public TtfOffsetTable OffsetTable;

        public List<string> TableDictionaryNamesInOrder = new List<string>();
        public List<string> TableOrders = new List<string>();

        [XmlIgnore]
        public Dictionary<string, TtfTableDictionary> TableDictionaries = new Dictionary<string, TtfTableDictionary>();

        public TtfTableDictionary[] TableDictionaryArray
        {
            get { return TableDictionaries.Values.ToArray(); }
            set { foreach (var tableDict in value) TableDictionaries.Add(tableDict.TagAsString, tableDict); }
        }

        [XmlIgnore]
        public Dictionary<string, object> Tables = new Dictionary<string, object>();

        [XmlIgnore]
        public Dictionary<string, byte[]> TableContents = new Dictionary<string, byte[]>();

        public OttHead Head;
        public OttHhea Hhea;
        public OttMaxp Maxp;
        public OttHmtx Hmtx;
        public OttOS2 OS2;
        public OttPost Post;
        public OttName Name;
        public OttLoca Loca;
        public OttCmap Cmap;
        public OttGlyf Glyf;

        public enum FileType
        {
            Unknown,
            Ttf,
            Xml
        };

        public void Save(Stream output, FileType fileType = FileType.Ttf)
        {
            switch (fileType)
            {
                case FileType.Ttf:
                    new TtfFileWriter(this, output).Write();
                    break;
                case FileType.Xml:
                    new XmlSerializer(this.GetType()).Serialize(output, this);
                    break;
                case FileType.Unknown:
                    throw new NotSupportedException("Please specify the file type!");
                    break;
            }
        }

        public static TtfFile Load(Stream input, FileType fileType = FileType.Ttf)
        {
            TtfFile result = null;

            switch (fileType)
            {
                case FileType.Ttf:
                    new TtfFileReader(result = new TtfFile(), input).Read();
                    break;
                case FileType.Xml:
                    result = (TtfFile)new XmlSerializer(typeof(TtfFile)).Deserialize(input);
                    break;
            }

            return result;
        }
    }
}
